<?php

namespace App\Admin\Controllers\Stat;

use App\Admin\Exports\StatDailyExport;
use App\Http\Controllers\Controller;
use App\Model\AppChannel;
use App\Model\PayOrder;
use App\Model\Stat\StatDaily;
use App\Model\Stat\StatDailyCoin;
use App\Model\Stat\StatOpeninstall;
use App\Model\User;
use App\Model\UserActLog;
use App\Model\UserProfile;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Log;

class StatDailyController extends Controller
{
    use ModelForm;

    public function index()
    {
        $this->super = Admin::user()->id == 1;
        $content = new Content();
        $content->header('统计数据日报');
        // $content->description('');
        $content->body($this->grid());
        return $content;
    }

    /**
     * $table->integer('active_total')->default(0)->comment('活跃总用户');
        $table->integer('active_male')->default(0)->comment('活跃男用户');
        $table->integer('active_host')->default(0)->comment('活跃女女用户');
        $table->integer('reg_total')->default(0)->comment('注册用户');
        $table->integer('reg_male')->default(0)->comment('注册男用户');
        $table->integer('reg_female')->default(0)->comment('注册女用户');
        $table->integer('recharge_num')->default(0)->comment('充值用户');
        $table->integer('recharge_coin')->default(0)->comment('充值金额（金币）');
        $table->integer('new_recharge_num')->default(0)->comment('新增充值用户');
        $table->integer('new_recharge_coin')->default(0)->comment('新增充值金额（金币）');
        $table->integer('consume_num')->default(0)->comment('消费用户');
        $table->integer('consume_coin')->default(0)->comment('消费金额（金币）');
        $table->char('channel', 10)->default('')->comment('注册渠道');
     */
    protected function grid()
    {
        $grid = new Grid(new StatDaily());
        if (!request()->dt) {
            request()->merge(['dt' => ['start' => date('Y-m-d', strtotime('-14 day')), 'end' => '']]);
        }
        $where = [];
        $grid->model()->orderBy('dt', 'desc')->orderBy('channel', 'desc');
        $grid->dt('日期');
        $channels = AppChannel::pluck('channel_name', 'channel');
        $grid->channel('注册渠道')->display(function ($data) use ($channels) {
            if ($data == 'all') return '全部渠道';
            return $channels[$data] ?? '-';
        });
        $grid->recharge_rmb('充值金额（元）')->display(function ($data) {
            return round($data / 100, 1);
        })->sortable();
        if ($this->super) {
            $grid->income_coin('女用户收入金币')->display(function ($data) {
                if (!$this->recharge_coin) return '';
                $percent = (round($data / $this->recharge_coin, 3) * 100) . " %";
                return $data . "<br/><br/>( {$percent} )";
            })->totalRow(function ($data) {
                return "<span class='text-danger text-bold'>总额：{$data}</span>";
            });
        }
        $grid->active_total('活跃用户总数');
        $grid->active_male('活跃男用户');
        $grid->active_host('活跃女用户');
        $grid->reg_total('注册用户');
        $grid->reg_male('注册男用户');
        $grid->reg_female('注册女用户');
        $grid->reg_host('认证主播数');
        $grid->reg_real_name('实名认证数');
//        $grid->reg_avatar_vrfied('真人认证数');
        $grid->recharge_num('充值用户');
        $grid->recharge_coin('充值金币');
        $grid->send_coin('赠送金币');
        $grid->new_recharge_num('新增充值用户');
        $grid->new_recharge_rmb('新增充值金额')->display(function ($data) {
            return round($data / 100, 1);
        })->sortable();
        $grid->recharge_percent('充值转化率（新增充值用户/注册男用户）')->display(function ($data) {
            return $this->reg_male ? round($this->new_recharge_num / $this->reg_male, 4) * 100 . '%' : '-';
        });
        $grid->consume_num('消费用户');
        // $grid->consume_coin('消费金币');
        $grid->withdraw_num('提现人数');
        $grid->withdraw_coin('提现金额')->display(function ($data) {
            if ($this->dt >= '2022-02-01') return round($data * 0.1 * config('busi.withdraw_percent'), 1);
            return round($data * 0.1, 1);
        })->sortable();
        $grid->total_user_num('总用户数（不含未完成注册的）');
        $grid->total_host_num('总女用户数');
        $grid->footer(function ($query) {
            $dtRange = request('dt');
            $channel = request('channel');
            if (!$channel) return '';
            if (empty($dtRange)) {
                $start = '2021-08-06';
                $end = '';
            } else {
                $start = $dtRange['start'] ?: '2021-08-06';
                $end = $dtRange['end'] ? date('Y-m-d', strtotime($dtRange['end']) + 24 * 3600) : '';
            }
            $statInfo = StatDaily::checkTotalReg($start, $end, $channel);
            if (is_array($channel) && $channel[0] == 'all') $channel = '';

            $totalCoin = StatDaily::orderby('id', 'desc')->first();
            // $channel == 'all' && $channel = '';
            $data = [
                'reg_total' => $statInfo->reg,
                'recharge_rmb' => round($statInfo->rmb / 100, 1),
                'active_total' => UserActLog::checkActiveCount([], $start, $end, $channel),
                'recharge_num' => PayOrder::getRechargeCount($start, $end, $channel),
                'new_recharge_num' => PayOrder::getNewRechargeCount($start, $end, $channel, 'user'),
                'new_recharge_rmb' => round(PayOrder::getNewRechargeCount($start, $end, $channel, 'rmb') / 10, 1),
            ];

            // Log::info(__CLASS__ . "==Start:" . json_encode($start) . "==End:" . json_encode($end) . "==Channel:" . json_encode($channel) . "==" . json_encode($data));
            $data['recharge_transfer'] =  $data['reg_total'] ? round($data['new_recharge_num'] / $data['reg_total'], 3) * 100 : 0;
            return '<table class="table custom-data-table data-table">
            <thead>
            <tr>
                <th>汇总：</th>
                <th>注册数（累计）：' . $data['reg_total'] . '</th>
                <th>充值金额（累计）：' . $data['recharge_rmb'] . '元</th>
                <th>充值数（去重）：' . $data['recharge_num'] . '</th>
                <th>活跃数（去重）：' . $data['active_total'] . '</th>
                <th>新增充值数（去重）：' . $data['new_recharge_num'] . '</th>
                <th>新增充值额（累计）：' . $data['new_recharge_rmb'] . '元</th>
                <th>充值转化（平均）：' . $data['recharge_transfer'] . '%</th>
            </tr>

            </thead></table>';
        });

        // $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->exporter(new StatDailyExport($grid));
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->between('dt', '日期')->date();
            });
            $filter->column(1 / 3, function ($filter) {
                // $filter->equal('channel', '渠道')->select('/get_channels');
                $filter->in('channel', '渠道')->multipleSelect('/get_channels');
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });
        return $grid;
    }

    function getChannels()
    {
        $channel = request('channel');
        $data = [['id' => 'all', 'text' => '全部渠道']];
        if ($channel == 'all') return $data;
        $where = ['flag' => 1];
        $list = AppChannel::where($where)->select(['channel_name', 'channel'])->get()->toArray();
        foreach ($list as $item) {
            $data[] = ['id' => $item['channel'], 'text' => $item['channel_name']];
        }
        return $data;
    }

    public function index_coin()
    {
        $content = new Content();
        $content->header('消费统计日报（金币）');
        $content->body($this->grid_coin());
        return $content;
    }

    public function index_openinstall()
    {
        $content = new Content();
        $content->header('OpenInstall数据日报');
        $content->body($this->grid_openinstall());
        return $content;
    }

    /**
     * $table->double('total_consume', 10, 1)->default(0.0)->comment('总消费金币');
            $table->double('video_consume', 10, 1)->default(0.0)->comment('视频消费金币');
            $table->double('voice_consume', 10, 1)->default(0.0)->comment('语音消费金币');
            $table->double('gift_consume', 10, 1)->default(0.0)->comment('礼物消费金币');
            $table->double('msg_consume', 10, 1)->default(0.0)->comment('私信消费金币');
            $table->double('other_consume', 10, 1)->default(0.0)->comment('其他消费金币');
     */
    protected function grid_coin()
    {
        $grid = new Grid(new StatDailyCoin());
        $grid->model()->orderBy('dt', 'desc')->orderBy('channel', 'desc');
        $grid->dt('日期');
        $channels = AppChannel::pluck('channel_name', 'channel');
        $grid->channel('注册渠道')->display(function ($data) use ($channels) {
            if ($data == 'all') return '全部渠道';
            return $channels[$data] ?? '-';
        });
        // $grid->total_consume('总消费')->display(function ($data) {
        //     $where = ['dt' => $this->dt, 'channel' => 'all'];
        //     $data = StatDaily::where($where)->first();
        //     return $data ? $data->consume_coin : 0;
        // });
        $grid->video_consume('视频通话消费（占比）')->display(function ($data) {
            return !$this->total_consume ? '-' : $data . "（" . round($data / $this->total_consume, 3) * 100 . "%）";
        });
        $grid->voice_consume('语音通话消费（占比）')->display(function ($data) {
            return !$this->total_consume ? '-' : $data . "（" . round($data / $this->total_consume, 3) * 100 . "%）";
        });
        $grid->gift_consume('礼物消费（占比）')->display(function ($data) {
            return !$this->total_consume ? '-' : $data . "（" . round($data / $this->total_consume, 3) * 100 . "%）";
        });
        $grid->msg_consume('私信消费（占比）')->display(function ($data) {
            return !$this->total_consume ? '-' : $data . "（" . round($data / $this->total_consume, 3) * 100 . "%）";
        });
        $grid->other_consume('其他消费（占比）')->display(function ($data) {
            return !$this->total_consume ? '-' : $data . "（" . round($data / $this->total_consume, 3) * 100 . "%）";
        });
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->date('dt', '日期');
            });
            $filter->column(1 / 3, function ($filter) {
                // $filter->equal('channel', '渠道')->select('/get_channels');
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });
        return $grid;
    }


    /**
     * $table->integer('install')->default(0)->comment('安装数');
        $table->integer('register')->default(0)->comment('注册数');
        $table->integer('survive_d1')->default(0)->comment('1日留存');
        $table->integer('survive_d7')->default(0)->comment('7日留存');
        $table->integer('survive_d30')->default(0)->comment('30日留存');
     */
    protected function grid_openinstall()
    {
        $grid = new Grid(new StatOpeninstall());
        $grid->model()->orderBy('dt', 'desc')->orderBy('channel', 'desc');
        $grid->dt('日期');
        $channels = AppChannel::pluck('channel_name', 'channel');
        $grid->channel('注册渠道')->display(function ($data) use ($channels) {
            if ($data == 'all') return '全部渠道';
            return $channels[$data] ?? '-';
        });
        $grid->install('安装数');
        $grid->register('注册数');
        $grid->survive_d1('次日留存');
        $grid->survive_d7('7日留存');
        $grid->survive_d30('30日留存');
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->date('dt', '日期');
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('channel', '渠道')->select('/get_channels');
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });
        return $grid;
    }
}
